from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import subprocess
import os
import tempfile
import uuid
from datetime import datetime
from pathlib import Path

app = Flask(__name__)
CORS(app)

# 工作目录配置
UPLOAD_FOLDER = tempfile.mkdtemp()
OUTPUT_FOLDER = tempfile.mkdtemp()
BPG_PATH = os.path.join(os.path.dirname(__file__), 'bpg.pyc')

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB max file size

# 存储生成任务的状态
tasks = {}

def run_bpg_command(command, input_file, output_file, outline_file=None):
    """执行BPG命令"""
    try:
        cmd = ['python3', BPG_PATH, command, '-i', input_file, '-o', output_file]
        if outline_file and command == 'full':
            cmd.extend(['--outline', outline_file])

        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=300  # 5分钟超时
        )

        return {
            'success': result.returncode == 0,
            'stdout': result.stdout,
            'stderr': result.stderr,
            'returncode': result.returncode
        }
    except subprocess.TimeoutExpired:
        return {
            'success': False,
            'error': '命令执行超时'
        }
    except Exception as e:
        return {
            'success': False,
            'error': str(e)
        }

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        'status': 'ok',
        'timestamp': datetime.now().isoformat()
    })

@app.route('/api/extract', methods=['POST'])
def extract():
    """提取技术内容"""
    if 'file' not in request.files:
        return jsonify({'error': '没有上传文件'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '文件名为空'}), 400

    # 保存上传的文件
    task_id = str(uuid.uuid4())
    input_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{task_id}_input.md')
    output_path = os.path.join(app.config['OUTPUT_FOLDER'], f'{task_id}_extract.md')

    file.save(input_path)

    # 执行提取命令
    result = run_bpg_command('extract', input_path, output_path)

    if result['success']:
        # 读取生成的文件
        with open(output_path, 'r', encoding='utf-8') as f:
            content = f.read()

        return jsonify({
            'success': True,
            'content': content,
            'task_id': task_id,
            'filename': f'技术要求_{datetime.now().strftime("%Y%m%d_%H%M%S")}.md'
        })
    else:
        return jsonify({
            'success': False,
            'error': result.get('stderr', result.get('error', '未知错误'))
        }), 500

@app.route('/api/outline', methods=['POST'])
def outline():
    """生成技术提纲"""
    if 'file' not in request.files:
        return jsonify({'error': '没有上传文件'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '文件名为空'}), 400

    # 保存上传的文件
    task_id = str(uuid.uuid4())
    input_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{task_id}_input.md')
    output_path = os.path.join(app.config['OUTPUT_FOLDER'], f'{task_id}_outline.md')

    file.save(input_path)

    # 执行提纲生成命令
    result = run_bpg_command('outline', input_path, output_path)

    if result['success']:
        # 读取生成的文件
        with open(output_path, 'r', encoding='utf-8') as f:
            content = f.read()

        return jsonify({
            'success': True,
            'content': content,
            'task_id': task_id,
            'filename': f'技术提纲_{datetime.now().strftime("%Y%m%d_%H%M%S")}.md'
        })
    else:
        return jsonify({
            'success': False,
            'error': result.get('stderr', result.get('error', '未知错误'))
        }), 500

@app.route('/api/full', methods=['POST'])
def full():
    """生成完整技术文档"""
    if 'file' not in request.files:
        return jsonify({'error': '没有上传技术要求文件'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '文件名为空'}), 400

    # 保存上传的文件
    task_id = str(uuid.uuid4())
    input_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{task_id}_input.md')
    output_path = os.path.join(app.config['OUTPUT_FOLDER'], f'{task_id}_full.md')

    file.save(input_path)

    # 检查是否有提纲文件
    outline_path = None
    if 'outline' in request.files and request.files['outline'].filename != '':
        outline_file = request.files['outline']
        outline_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{task_id}_outline.md')
        outline_file.save(outline_path)

    # 执行完整文档生成命令
    result = run_bpg_command('full', input_path, output_path, outline_path)

    if result['success']:
        # 读取生成的文件
        with open(output_path, 'r', encoding='utf-8') as f:
            content = f.read()

        return jsonify({
            'success': True,
            'content': content,
            'task_id': task_id,
            'filename': f'完整技术文档_{datetime.now().strftime("%Y%m%d_%H%M%S")}.md'
        })
    else:
        return jsonify({
            'success': False,
            'error': result.get('stderr', result.get('error', '未知错误'))
        }), 500

@app.route('/api/download/<task_id>', methods=['GET'])
def download(task_id):
    """下载生成的文件"""
    file_type = request.args.get('type', 'full')
    output_path = os.path.join(app.config['OUTPUT_FOLDER'], f'{task_id}_{file_type}.md')

    if not os.path.exists(output_path):
        return jsonify({'error': '文件不存在'}), 404

    return send_file(
        output_path,
        as_attachment=True,
        download_name=f'{file_type}_{datetime.now().strftime("%Y%m%d_%H%M%S")}.md'
    )

if __name__ == '__main__':
    print(f"上传文件夹: {UPLOAD_FOLDER}")
    print(f"输出文件夹: {OUTPUT_FOLDER}")
    print(f"BPG路径: {BPG_PATH}")
    app.run(debug=True, host='0.0.0.0', port=5000)
